//
//  MYStringTool.m
//  LedemonBase
//
//  Created by YiDian on 2019/7/17.
//

#import "MYStringTool.h"

@implementation MYStringTool

+(NSAttributedString *)setString:(NSString *)str withColorOneStr:(NSString *)oneStr andColorOne:(UIColor *)colorOne andColorTwoStr:(NSString *)twoStr andColorTwo:(UIColor *)colorTwo{
    
    NSMutableAttributedString *hintString=[[NSMutableAttributedString alloc]initWithString:str];
    NSRange range1=[[hintString string]rangeOfString:oneStr];
    [hintString addAttribute:NSForegroundColorAttributeName value:colorOne range:range1];
    NSRange range2=[[hintString string]rangeOfString:twoStr];
    [hintString addAttribute:NSForegroundColorAttributeName value:colorTwo range:range2];
    return hintString;
}

+(CGFloat)getHeightWithString:(NSString *)string Font:(CGFloat)font fontName:(NSString *)fontName width:(CGFloat)width{
    //计算内容size
    CGSize textMaxSize = CGSizeMake(width, MAXFLOAT);
    CGFloat height = [string boundingRectWithSize:textMaxSize options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName : [UIFont fontWithName:fontName size:font]} context:nil].size.height;
    //    return contentSize.height;
    return height;
}

+ (CGFloat)getWidthWithString:(NSString *)test Font:(CGFloat)font fontName:(NSString *)fontName{
    if (fontName == nil) {
        CGRect rect = [test boundingRectWithSize:CGSizeMake(MAXFLOAT, 20) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:font]} context:nil];
        return rect.size.width;
    }
    CGRect rect = [test boundingRectWithSize:CGSizeMake(MAXFLOAT, 20) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName:[UIFont fontWithName:fontName size:font]} context:nil];
    return rect.size.width;
}

+(NSString *)stringWithDict:(NSDictionary *)dict{
    NSMutableString *tem = [NSMutableString stringWithCapacity:1];
    [tem appendString:@"{"];
    NSArray *keys = [dict allKeys];
    for (NSString *key in keys) {
        [tem appendString:[NSString stringWithFormat:@"\"%@\":%@,",key,[dict objectForKey:key]]];
    }
    NSString *tem1 = [tem substringToIndex:[tem length]-1];
    
    return [NSString stringWithFormat:@"%@}",tem1];
}

+(NSString *)stringWithArr:(NSArray *)arr{
    if (arr.count == 0) {
        return @"";
    }
    NSMutableString *tem = [NSMutableString stringWithCapacity:1];
    for (NSString *key in arr) {
        [tem appendString:[NSString stringWithFormat:@"%@,",key]];
    }
    NSString *tem1 = [tem substringToIndex:[tem length]-1];
    
    return tem1;
}

+(NSString *)stringWithDuration:(NSInteger)duration{
    NSString * str = @"";
    NSString *minutesStr = @"";
    NSString *secondsStr = @"";
    
    int hours = duration/3600;
    int minutes = (duration%3600)/60;
    int seconds = (duration%3600)%60;
    if (hours != 0) {
        if (minutes < 10) {
            minutesStr = [NSString stringWithFormat:@"0%i",minutes];
        }else{
            minutesStr = [NSString stringWithFormat:@"%i",minutes];
        }
        if (seconds < 10) {
            secondsStr = [NSString stringWithFormat:@"0%i",seconds];
        }else{
            secondsStr = [NSString stringWithFormat:@"%i",seconds];
        }
        str = [NSString stringWithFormat:@"%i:%@:%@",hours,minutesStr,secondsStr];
    }else if(minutes != 0){
        if (seconds < 10) {
            secondsStr = [NSString stringWithFormat:@"0%i",seconds];
        }else{
            secondsStr = [NSString stringWithFormat:@"%i",seconds];
        }
        str = [NSString stringWithFormat:@"%i:%@",minutes,secondsStr];
    }else{
        if (seconds < 10) {
            secondsStr = [NSString stringWithFormat:@"00:0%i",seconds];
        }else{
            secondsStr = [NSString stringWithFormat:@"00:%i",seconds];
        }
        str = [NSString stringWithFormat:@"%@",secondsStr];
    }
    return str;
}

+(NSString *)stringWithchannelName:(NSString *)channelName playNum:(NSString *)playNum createTime:(NSString *)createTime{
    NSString *playNumStr = [self stringWithplayNum:playNum];
    NSString *createTimeStr = [self stringWithTime:createTime];
    return [NSString stringWithFormat:@"%@ • %@ • %@",channelName,playNumStr,createTimeStr];
}

+(NSString *)stringWithchannelName:(NSString *)channelName playNum:(NSString *)playNum{
    NSString *playNumStr = [self stringWithplayNum:playNum];
    return [NSString stringWithFormat:@"%@ • %@",channelName,playNumStr];
}


+(NSString *)stringWithplayNum:(NSString *)playNum{
    NSString *tem = @"";
    int num = [playNum intValue];
    if (num > 10000) {
        tem = [NSString stringWithFormat:@"%i万次观看", num/10000];
    }else{
        tem = [NSString stringWithFormat:@"%i次观看", num];
    }
    return tem;
}

+(NSString *)stringWithloveNum:(NSString *)loveNum{
    NSString *tem = @"";
    int num = [loveNum intValue];
    if (num > 10000) {
        tem = [NSString stringWithFormat:@"%i万", num/10000];
    }else{
        tem = [NSString stringWithFormat:@"%i", num];
    }
    return tem;
}

+(NSString *)stringWithSubscribeNum:(NSString *)subscribeNum{
    NSString *tem = @"";
    int num = [subscribeNum intValue];
    if (num > 10000) {
        float temFloat = [subscribeNum floatValue];
        if ((num%10000)/1000 == 0) {
            tem = [NSString stringWithFormat:@"%i万粉丝", num/10000];
        }else{
            tem = [NSString stringWithFormat:@"%.1f万粉丝", temFloat/10000];
        }
    }else{
        tem = [NSString stringWithFormat:@"%i粉丝", num];
    }
    return tem;
}

+(NSString *)stringWithNum:(NSString *)num{
    NSString *tem = @"";
    int temNum = [num intValue];
    if (temNum > 10000) {
        float temFloat = [num floatValue];
        
        if ((temNum%10000)/1000 == 0) {
            tem = [NSString stringWithFormat:@"%i万", temNum/10000];
        }else{
            tem = [NSString stringWithFormat:@"%.1f万", temFloat/10000];
        }
    }else{
        tem = [NSString stringWithFormat:@"%i", temNum];
    }
    return tem;
}

+(NSString *)stringWithTime:(NSString *)time{
    NSString *temStr = @"";
    NSDate* currentDate = [NSDate date];
    
    // 格式化时间
    NSDateFormatter* formatter = [[NSDateFormatter alloc] init];
    formatter.timeZone = [NSTimeZone timeZoneWithName:@"shanghai"];
    [formatter setDateStyle:NSDateFormatterMediumStyle];
    [formatter setTimeStyle:NSDateFormatterShortStyle];
    [formatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    
    // 毫秒值转化为秒
    NSDate* date = [NSDate dateWithTimeIntervalSince1970:[time doubleValue]/ 1000.0];
    
    NSCalendar *gregorian = [NSCalendar currentCalendar];
    
    NSCalendarUnit type = NSCalendarUnitYear|NSCalendarUnitMonth|NSCalendarUnitDay|NSCalendarUnitHour|NSCalendarUnitMinute|NSCalendarUnitSecond;
    
    NSDateComponents *comps = [gregorian components:type fromDate:date  toDate:currentDate options:0];
    
    NSInteger year = [comps year];
    if (year != 0) {
        return [NSString stringWithFormat:@"%li年前",(long)year];
    }else{
        NSInteger tem = [comps month];
        if (tem != 0) {
            return [NSString stringWithFormat:@"%li月前",(long)tem];
        }else{
            NSInteger tem = [comps day];
            if (tem != 0) {
                return [NSString stringWithFormat:@"%li日前",(long)tem];
            }else{
                NSInteger tem = [comps hour];
                if (tem != 0) {
                    return [NSString stringWithFormat:@"%li小时前",(long)tem];
                }else{
                    NSInteger tem = [comps minute];
                    if (tem != 0) {
                        return [NSString stringWithFormat:@"%li分前",(long)tem];
                    }else{
                        temStr = @"刚刚";
                    }
                }
            }
        }
    }
    
    return temStr;
}


+(NSString *)stringWithcreateTime:(NSString *)createTime{
    // 格式化时间
    NSDateFormatter* formatter = [[NSDateFormatter alloc] init];
    formatter.timeZone = [NSTimeZone timeZoneWithName:@"shanghai"];
    [formatter setDateStyle:NSDateFormatterMediumStyle];
    [formatter setTimeStyle:NSDateFormatterShortStyle];
    [formatter setDateFormat:@"yyyy年MM月dd日"];
    
    // 毫秒值转化为秒
    NSDate* date = [NSDate dateWithTimeIntervalSince1970:[createTime doubleValue]/ 1000.0];
    NSString *dateString = [formatter stringFromDate: date];
    
    return [NSString stringWithFormat:@"%@发布",dateString];
}

+(NSString *)dateStringWithcreateTime:(NSString *)createTime{
    // 格式化时间
    NSDateFormatter* formatter = [[NSDateFormatter alloc] init];
    formatter.timeZone = [NSTimeZone timeZoneWithName:@"shanghai"];
    [formatter setDateStyle:NSDateFormatterMediumStyle];
    [formatter setTimeStyle:NSDateFormatterShortStyle];
    [formatter setDateFormat:@"yyyy年MM月dd日"];
    
    // 毫秒值转化为秒
    NSDate* date = [NSDate dateWithTimeIntervalSince1970:[createTime doubleValue]/ 1000.0];
    NSString *dateString = [formatter stringFromDate: date];
    
    return dateString;
}

//"电影","动画","音乐","宠物和动物","体育","旅游和活动","游戏","人物和博客","喜剧","娱乐","新闻和政治","DIT和生活百科","教育","科学与技术","公益与社会活动","汽车","TV剧"
+(NSString *)stringWithTvType:(int)tvType{
    NSArray *typeArr = @[@"电影",@"动画",@"音乐",@"宠物和动物",@"体育",@"旅游和活动",@"游戏",@"人物和博客",@"喜剧",@"娱乐",@"新闻和政治",@"DIT和生活百科",@"教育",@"科学与技术",@"公益与社会活动",@"汽车",@"TV剧"];
    if (tvType <= 0) {
        tvType = 1;
    }
    int i = tvType - 1;
    return typeArr[i];
}

+(NSString *)stringWithLicense:(NSString *)license{
    return @"Fantasy许可";
}

#pragma 正则匹配手机号
+ (BOOL)checkTelNumber:(NSString *) telNumber
{
    NSString *pattern = @"^1+[0123456789]+\\d{9}";
    NSPredicate *pred = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", pattern];
    BOOL isMatch = [pred evaluateWithObject:telNumber];
    return isMatch;
}


#pragma 正则匹配手机号/电话
+ (BOOL)checkPhoneNumber:(NSString *) telNumber
{
    NSString *pattern = @"^[1-9]+[0123456789]+\\d{9}";
    NSPredicate *pred = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", pattern];
    BOOL isMatch = [pred evaluateWithObject:telNumber];
    return isMatch;
}

//邮箱
+ (BOOL) checkEmail:(NSString *)email
{
    NSString *emailRegex = @"[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}";
    NSPredicate *emailTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", emailRegex];
    return [emailTest evaluateWithObject:email];
}

#pragma 正则匹配用户密码6-16位数字和字母组合
+ (BOOL)checkPassword:(NSString *) password
{
    NSString *pattern = @"^[0-9a-zA-Z_#@]{6,16}";
    //    NSString *pattern = @"^(?![0-9]+$)(?![a-zA-Z]+$)[a-zA-Z0-9]{6,16}";
    NSPredicate *pred = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", pattern];
    BOOL isMatch = [pred evaluateWithObject:password];
    return isMatch;
    
}
#pragma 正则匹配验证码
+ (BOOL)checkVerCode:(NSString *) verCode
{
    NSString *pattern = @"^\\d{4,6}";
    NSPredicate *pred = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", pattern];
    BOOL isMatch = [pred evaluateWithObject:verCode];
    return isMatch;
}

#pragma 正则匹配用户姓名,20位的中文或英文
+ (BOOL)checkUserName : (NSString *) userName
{
    NSString *pattern = @"^[0-9a-zA-Z\u4E00-\u9FA5]{1,20}";
    NSPredicate *pred = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", pattern];
    BOOL isMatch = [pred evaluateWithObject:userName];
    return isMatch;
    
}

#pragma 正则匹配标签：中文或英文
+ (BOOL)checkTag : (NSString *) tag
{
    NSString *pattern = @"^[a-zA-Z\u4E00-\u9FA5]{1,10}";
    
    
    
    NSPredicate *pred = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", pattern];
    BOOL isMatch = [pred evaluateWithObject:tag];
    return isMatch;
    
}

#pragma 正则匹配用户身份证号15或18位
+ (BOOL)checkUserIdCard: (NSString *) idCard
{
    NSString *pattern = @"(^[0-9]{15}$)|([0-9]{17}([0-9]|X)$)";
    NSPredicate *pred = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", pattern];
    BOOL isMatch = [pred evaluateWithObject:idCard];
    return isMatch;
}

#pragma 正则匹员工号,12位的数字
+ (BOOL)checkEmployeeNumber : (NSString *) number
{
    NSString *pattern = @"^[0-9]{12}";
    
    NSPredicate *pred = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", pattern];
    BOOL isMatch = [pred evaluateWithObject:number];
    return isMatch;
    
}

#pragma 正则匹配URL
+ (BOOL)checkURL : (NSString *) url
{
    NSString *pattern = @"^[0-9A-Za-z]{1,50}";
    NSPredicate *pred = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", pattern];
    BOOL isMatch = [pred evaluateWithObject:url];
    return isMatch;
}

+(void)TextGradientview:(UIView *)view bgVIew:(UIView *)bgVIew gradientColors:(NSArray *)colors gradientStartPoint:(CGPoint)startPoint endPoint:(CGPoint)endPoint{
    
    CAGradientLayer* gradientLayer1 = [CAGradientLayer layer];
    gradientLayer1.frame = view.frame;
    gradientLayer1.colors = colors;
    gradientLayer1.startPoint =startPoint;
    gradientLayer1.endPoint = endPoint;
    [bgVIew.layer addSublayer:gradientLayer1];
    gradientLayer1.mask = view.layer;
    view.frame = gradientLayer1.bounds;
}

+ (NSString *)translation:(NSString *)arebic

{   NSString *str = arebic;
    NSArray *arabic_numerals = @[@"1",@"2",@"3",@"4",@"5",@"6",@"7",@"8",@"9",@"0"];
    NSArray *chinese_numerals = @[@"一",@"二",@"三",@"四",@"五",@"六",@"七",@"八",@"九",@"零"];
    NSArray *digits = @[@"个",@"十",@"百",@"千",@"万",@"十",@"百",@"千",@"亿",@"十",@"百",@"千",@"兆"];
    NSDictionary *dictionary = [NSDictionary dictionaryWithObjects:chinese_numerals forKeys:arabic_numerals];
    
    NSMutableArray *sums = [NSMutableArray array];
    for (int i = 0; i < str.length; i ++) {
        NSString *substr = [str substringWithRange:NSMakeRange(i, 1)];
        NSString *a = [dictionary objectForKey:substr];
        NSString *b = digits[str.length -i-1];
        NSString *sum = [a stringByAppendingString:b];
        if ([a isEqualToString:chinese_numerals[9]])
        {
            if([b isEqualToString:digits[4]] || [b isEqualToString:digits[8]])
            {
                sum = b;
                if ([[sums lastObject] isEqualToString:chinese_numerals[9]])
                {
                    [sums removeLastObject];
                }
            }else
            {
                sum = chinese_numerals[9];
            }
            
            if ([[sums lastObject] isEqualToString:sum])
            {
                continue;
            }
        }
        
        [sums addObject:sum];
    }
    
    NSString *sumStr = [sums  componentsJoinedByString:@""];
    NSString *chinese = [sumStr substringToIndex:sumStr.length-1];
    //    NSLog(@"str %@",str);
    NSLog(@"%s  %@", __func__, chinese);
    return chinese;
}

#pragma mark - 获取这个字符串ASting中的所有abc的所在的index
+ (NSMutableArray *)getRangeStr:(NSString *)text findText:(NSString *)findText {
    NSMutableArray *arrayRanges = [NSMutableArray arrayWithCapacity:3];
    if (findText == nil && [findText isEqualToString:@""]) {
        return nil;
    }
    NSRange rang = [text rangeOfString:findText]; //获取第一次出现的range
    if (rang.location != NSNotFound && rang.length != 0) {
        [arrayRanges addObject:[NSNumber numberWithInteger:rang.location]];//将第一次的加入到数组中
        NSRange rang1 = {0,0};
        NSInteger location = 0;
        NSInteger length = 0;
        for (int i = 0;; i++) {
            if (0 == i) {
                //去掉这个abc字符串
                location = rang.location + rang.length;
                length = text.length - rang.location - rang.length;
                rang1 = NSMakeRange(location, length);
            } else {
                location = rang1.location + rang1.length;
                length = text.length - rang1.location - rang1.length;
                rang1 = NSMakeRange(location, length);
            }
            //在一个range范围内查找另一个字符串的range
            rang1 = [text rangeOfString:findText options:NSCaseInsensitiveSearch range:rang1];
            if (rang1.location == NSNotFound && rang1.length == 0) {
                break;
            } else//添加符合条件的location进数组
                [arrayRanges addObject:[NSNumber numberWithInteger:rang1.location]];
        }
        return arrayRanges;
    }
    return nil;
}

@end
